package com.example.shoppingmall.cotroller;

import com.alibaba.fastjson.JSONArray;
import com.example.shoppingmall.config.FingerPrint;
import com.example.shoppingmall.pojo.Note;
import com.example.shoppingmall.pojo.Page;
import com.example.shoppingmall.pojo.User;
import com.example.shoppingmall.service.NoteService;
import com.example.shoppingmall.service.sms.SMSCode_register;
import com.example.shoppingmall.service.UserService;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SMSCode_register smsCode_register;
    @Autowired
    private UserService userService;
    @Autowired
    private NoteService noteService;

    public void setSmsCode_register(SMSCode_register smsCode_register) {
        this.smsCode_register = smsCode_register;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setNoteService(NoteService noteService) {
        this.noteService = noteService;
    }

    /**
     * 用户列表查询
     *
     * @param userPhone
     * @param username
     * @param inviterPhone
     * @param no
     * @param session
     * @return
     */
    @RequestMapping(value = "/toUserList")
    public String toUserList(
            @RequestParam(value = "userPhone", required = false) String userPhone,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "inviterPhone", required = false) String inviterPhone,
            @RequestParam(value = "no", required = false) String no,
            HttpSession session,Model model) {
        model.addAttribute("userPhone",userPhone);
        model.addAttribute("username",username);
        model.addAttribute("inviterPhone",inviterPhone);
        int curr = 1;
        Page page = new Page();
        int count = userService.userCount(userPhone,username,inviterPhone);
        page.setCount(count);
        if (no != null) {
            curr = Integer.parseInt(no);
            if (curr > page.getPageSum()) {
                curr = page.getPageSum();
            } else if (curr < 1) {
                curr = 1;
            }
        }
        page.setPageNo(curr);
        List<User> userList = userService.getAll(userPhone, username, inviterPhone, (curr - 1) * 6);
        session.setAttribute("page", page);
        session.setAttribute("userList", userList);
        return "user/userList";
    }


    /**
     * 用户信息注册
     *
     * @param userPhone
     * @param username
     * @param userPassword
     * @param userSex
     * @param userBirthday
     * @param userStatus
     * @param files
     * @param request
     * @return
     */
    @RequestMapping(value = "/toUserAdd")
    public String toUserAdd(@RequestParam("userPhone") String userPhone,@RequestParam("userAccount") String userAccount,
                            @RequestParam("username") String username, @RequestParam("userPassword") String userPassword,
                            @RequestParam("userSex") String userSex, @RequestParam("userBirthday") String userBirthday,
                            @RequestParam("userStatus") String userStatus, MultipartFile files, HttpServletRequest request) throws Exception {
        User user = new User();
        String path =("D:\\shoppingmall\\src\\main\\resources\\static\\images");
        File file = new File(path);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        String oldname = files.getOriginalFilename();
        String newname = UUID.randomUUID().toString() + oldname.substring(oldname.lastIndexOf("."), oldname.length());
        try {
            files.transferTo(new File(file, newname));
        } catch (IOException e) {
            e.printStackTrace();
        }
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(10);
        String encoderpwd=encoder.encode(userPassword);
        user.setUserAccount(userAccount);
        user.setUserImgPath(newname);
        user.setUserPhone(userPhone);
        user.setUserPassword(encoderpwd);



        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword("4s56ggdf");
        String u1= textEncryptor.encrypt(userPassword);
        user.setPwd2(u1);



        user.setUsername(username);
        user.setUserSex(Integer.parseInt(userSex));
        user.setUserBirthday(userBirthday);
        user.setUserStatus(Integer.parseInt(userStatus));
        int rs = userService.add(user);
        if (rs > 0) {
            //发短信
            //smsCode_register.sendCode(userPhone);
            //存短信
            Note note=new Note();
            note.setPhone(userPhone);
            note.setTypeId(1);
            note.setContentId(1);
            noteService.add(note);
            return "redirect:toUserList";
        } else {
            return "edirect:toUserList";
        }
    }

    /**
     * 查看详情
     *
     * @param session
     * @param id
     * @return
     */
    @RequestMapping(value = "/toXiangqing")
    public String toXiangqing(HttpSession session, @RequestParam("id") String id) {
        User user = userService.xiangqing(Integer.parseInt(id));
        session.setAttribute("user", user);
        return "user/userUpdate";
    }

    /**
     * 修改操作
     * @param id
     * @param userPhone
     * @param username
     * @param userSex
     * @param userBirthday
     * @param userStatus
     * @param request
     * @return
     */
    @RequestMapping(value = "/toUserUpdate")
    public String toUserUpdate(
            @RequestParam("id") String id,
            @RequestParam("userPhone") String userPhone,
            @RequestParam("username") String username,
            @RequestParam("userSex") String userSex, @RequestParam("userBirthday") String userBirthday,
            @RequestParam("imgfiles") String imgfiles,
            @RequestParam("userStatus") String userStatus, HttpServletRequest request) {
        User user = new User();

        if (imgfiles!=null) {  //判断是否重新上传了图片
            String path="D:\\shoppingmall\\src\\main\\resources\\static\\images\\";
            File file = new File(path);
            if (!file.isDirectory()) {
                file.mkdirs();
            }



            user.setId(Integer.parseInt(id));
            user.setUserPhone(userPhone);

            user.setUsername(username);
            user.setUserImgPath(imgfiles);
            user.setUserSex(Integer.parseInt(userSex));
            user.setUserBirthday(userBirthday);
            user.setUserStatus(Integer.parseInt(userStatus));
            int rs = userService.update(user);
            if (rs > 0) {
                return "redirect:toUserList";
            } else {
                return "user/userUpdate";
            }
        } else {


            user.setId(Integer.parseInt(id));
            user.setUserPhone(userPhone);
            user.setUsername(username);
            user.setUserSex(Integer.parseInt(userSex));
            user.setUserBirthday(userBirthday);
            user.setUserStatus(Integer.parseInt(userStatus));
            int rs = userService.update1(user);
            if (rs > 0) {
                return "redirect:toUserList";
            } else {
                return "user/userUpdate";
            }
        }
    }

    /**
     * 跳转到余额修改页面
     * @param id
     * @param session
     * @return
     */
    @RequestMapping(value = "/toUpdateUserBalance")
    public String toUpdateUserBalance(@RequestParam("id")String id,HttpSession session){
        User user=userService.xiangqing(Integer.parseInt(id));
        session.setAttribute("user",user);
        return "user/userBalanceUpdate";
    }

    /**
     * 余额修改
     * @param userBalance
     * @param id
     * @return
     */
    @RequestMapping(value = "/updateUserBalance")
    public String updateUserBalance(@RequestParam("userBalance")String userBalance,@RequestParam("userBalance1")String userBalance1,
                                    @RequestParam("id")String id,Model model){
        //如果原来余额小于修改余额的话
        Double number=Double.parseDouble(userBalance1)+Double.parseDouble(userBalance);
        System.out.println(number);
        if(number<0){
            model.addAttribute("error","余额不能小于0!");
            return "user/userBalanceUpdate";
        }
        User user=new User();
        user.setUserBalance(number);
        user.setId(Integer.parseInt(id));
        int rs=userService.updateUserBalance(user);
        if(rs>0){
            return "redirect:toUserList";
        }else{
            return "user/userBalanceUpdate";
        }
    }

    /**
     * 跳转到积分修改页面
     * @param id
     * @param session
     * @return
     */
    @RequestMapping(value = "/toUserIntegral")
    public String toUserIntegral(@RequestParam("id")String id,HttpSession session){
        User user=userService.xiangqing(Integer.parseInt(id));
        session.setAttribute("user",user);
        return "user/userIntegralUpdate";
    }

    /**
     * 积分修改
     * @param id
     * @param userIntegral
     * @return
     */
    @RequestMapping(value ="/UpdateUserIntegral" )
    public String UpdateUserIntegral(@RequestParam("id")String id, @RequestParam("userIntegral")String userIntegral,
                                     @RequestParam("userIntegral1")String userIntegral1, Model model){
        //如果原来积分小于修改积分的话
        int number=Integer.parseInt(userIntegral1)+Integer.parseInt(userIntegral);
        System.out.println(number);
        if(number<0){
            model.addAttribute("error","积分不能小于0!");
            return "user/userIntegralUpdate";
        }
        User user=new User();
        user.setUserIntegral(number);
        user.setId(Integer.parseInt(id));
        int rs=userService.updateUserIntegral(user);
        if(rs>0){
            return "redirect:toUserList";
        }else{
            return "user/userIntegralUpdate";
        }
    }

    /**
     * 跳转到修改联系人页面
     * @param id
     * @param session
     * @return
     */
    @RequestMapping(value = "/toUpdateInviterPhone")
    public String toUpdateInviterPhone(@RequestParam("id")String id,HttpSession session){
        User user=userService.xiangqing(Integer.parseInt(id));
        session.setAttribute("user",user);
        return "user/userinviterUpdate";
    }

    /**
     * 联系人修改
     * @param id
     * @param inviterPhone
     * @return
     */
    @RequestMapping(value ="/UpdateInviterPhone" )
    public String UpdateInviterPhone(@RequestParam("id")String id,@RequestParam("inviterPhone")String inviterPhone){
        User user=new User();
        user.setInviterPhone(inviterPhone);
        user.setId(Integer.parseInt(id));
        int rs=userService.updateInviterPhone(user);
        if(rs>0){
            return "redirect:toUserList";
        }else{
            return "user/userinviterUpdate";
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete")
    public String delete(@RequestParam("id")String id){
        int rs=userService.delete(Integer.parseInt(id));
        if(rs>0){
            return "redirect:toUserList";
        }else{
            return "redirect:toUserList";
        }
    }

    /**
     * 判断手机号是否存在
     * @param userPhone
     * @return
     */
    @RequestMapping(value="/chackUserPhone")
    @ResponseBody
    public Object chackUserPhone(@RequestParam("userPhone")String userPhone){
        User user=userService.checkUserPhone(userPhone);
        Map<Object,Object> map=new HashMap<Object, Object>();
        if(user!=null){
            map.put("checking", "exists");
        }else{
            map.put("checking", "no");
        }
        return JSONArray.toJSONString(map);
    }

    /**
     * 判断登录名是否存在
     *
     * @param userAccount
     * @return
     */
    @RequestMapping(value="/chackUserAccount")
    @ResponseBody
    public Object chackUserAccount(@RequestParam("userAccount")String userAccount){
        int rs=userService.chackUserAccount(userAccount);
        Map<Object,Object> map=new HashMap<Object, Object>();
        if(rs>0){
            map.put("checking", "exists");
        }else{
            map.put("checking", "no");
        }
        return JSONArray.toJSONString(map);
    }

    //图片哈希算法对比
    @RequestMapping("/photos")
    @ResponseBody
    public Map<Object,Object> photos(@RequestParam(value = "photos") String photos,@RequestParam(value = "img") String img,HttpSession session) {
        Map<Object, Object> map = new HashMap<>();
//        for (int h = 1; h <= 3; h++) {
//            String[] images = {"C:\\Users\\admin\\Downloads\\" + photos, img};
//            if (images.length == 0) {
//                System.out.println("Usage >java BMPLoader ImageFile.bmp");
//                System.exit(0);
//            }
//
//            // 分析图片相似度 begin
//            String[][] list1 = BMPLoader.getPX(images[0]);
//            String[][] list2 = BMPLoader.getPX(images[1]);
//            int xiangsi = 0;
//            int busi = 0;
//            int i = 0, j = 0;
//            for (String[] strings : list1) {
//                if ((i + 1) == list1.length) {
//                    continue;
//                }
//                for (int m = 0; m < strings.length; m++) {
//                    try {
//                        String[] value1 = list1[i][j].toString().split(",");
//                        String[] value2 = list2[i][j].toString().split(",");
//                        int k = 0;
//                        for (int n = 0; n < value2.length; n++) {
//                            if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
//                                xiangsi++;
//                            } else {
//                                busi++;
//                            }
//                        }
//                    } catch (RuntimeException e) {
//                        continue;
//                    }
//                    j++;
//                }
//                i++;
//            }
//
//            list1 = BMPLoader.getPX(images[1]);
//            list2 = BMPLoader.getPX(images[0]);
//            i = 0;
//            j = 0;
//            for (String[] strings : list1) {
//                if ((i + 1) == list1.length) {
//                    continue;
//                }
//                for (int m = 0; m < strings.length; m++) {
//                    try {
//                        String[] value1 = list1[i][j].toString().split(",");
//                        String[] value2 = list2[i][j].toString().split(",");
//                        int k = 0;
//                        for (int n = 0; n < value2.length; n++) {
//                            if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
//                                xiangsi++;
//                            } else {
//                                busi++;
//                            }
//                        }
//                    } catch (RuntimeException e) {
//                        continue;
//                    }
//                    j++;
//                }
//                i++;
//            }
//            String baifen = "";
//            try {
//                baifen = ((Double.parseDouble(xiangsi + "") / Double.parseDouble((busi + xiangsi) + "")) + "");
//                baifen = baifen.substring(baifen.indexOf(".") + 1, baifen.indexOf(".") + 3);
//            } catch (Exception e) {
//                baifen = "0";
//            }
//            if (baifen.length() <= 0) {
//                baifen = "0";
//            }
//            if (busi == 0) {
//                baifen = "100";
//            }
//
//            System.out.println("相似像素数量：" + xiangsi + " 不相似像素数量：" + busi + " 相似率：" + Integer.parseInt(baifen) + "%");
//
//            if (Integer.parseInt(baifen) > 10) {
//                map.put("photo", "yes");
//            } else {
//                map.put("photo", "no");
//            }
//        }
////        BMPLoader.compareImage("C:\\Users\\admin\\Downloads\\"+photos, "D:\\shoppingmall\\src\\main\\resources\\static\\images\\2.jpg");
//        return map;

        FingerPrint fp1 = null;
        try {
            String photo="D:\\Backup\\Downloads\\"+photos;
            fp1 = new FingerPrint(ImageIO.read(new File(photo)));
            FingerPrint fp2 =new FingerPrint(ImageIO.read(new File(img)));
            System.out.println(fp1.toString(true));
            System.out.printf("sim=%f",fp1.compare(fp2));
            if(fp1.compare(fp2)>0.80){
                User user= (User) session.getAttribute("user");
                String username=user.getUsername();
                System.out.println(username);
                String pwd=user.getPwd2();
                BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
                textEncryptor.setPassword("4s56ggdf");
                String u1= textEncryptor.decrypt(pwd);
                System.out.println(u1);
                map.put("usernames",username);
                map.put("pwd",u1);
                map.put("photo","yes");
            }else{
                map.put("photo","no");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    //同名验证
    @RequestMapping("/selname")
    @ResponseBody
    public Map<Object,Object> selname(@RequestParam("userAccount") String userAccount,HttpSession session){
        Map<Object,Object> map=new HashMap<>();
        User user=userService.getuserimg(userAccount);
        session.setAttribute("user",user);
        if(user!=null){
            String img=user.getPhoto();
            map.put("selname","yes");
            map.put("img",img);
        }else{
            map.put("selname","no");
        }
        return map;
    }
}